import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    listItems:[],
    cartItems:JSON.parse(localStorage.getItem("cartItems")) || [],
    allSelected:false,
    totalCount:0,
    totalPrice:0
  },
  mutations: {
    GET_LIST_DATA(state,items){
      state.listItems = [...items];
    },
    ADD_ITEM_TO_CART(state,item){
      //找到重复商品
      var flag = false;
      state.cartItems.forEach((element)=>{
        if(element.id === item.id){
          element.count++;
          flag = true;
        }
      })

      if(!flag){
        item.count = 1;
        item.checked = false;
        state.cartItems.push(item);
      }
      localStorage.setItem("cartItems",JSON.stringify(state.cartItems));
    },
    CHANGE_ITEM_STATUS(state,item){
      //找到商品 
      state.cartItems.forEach((element)=>{
        if(element.id === item.id){
          element.checked = item.checked
        }
      });

      //同步全选状态
      state.allSelected = state.cartItems.every((ele)=>{
        return ele.checked === true
      })

      //计算 总价 和 总量
      state.totalCount = 0;
      state.totalPrice = 0;
      state.cartItems.forEach((element)=>{
        if(element.checked){
          state.totalCount += element.count;
          state.totalPrice += (element.count*element.originalPrice);
        }
      }) 
    },
    CHANGE_ALL_SELECTED(state,boolean){
      state.allSelected  = boolean;
      state.cartItems.forEach((element)=>{
        element.checked = boolean
      });

      //计算 总价 和 总量
      state.totalCount = 0;
      state.totalPrice = 0;
      state.cartItems.forEach((element)=>{
        if(element.checked){
          state.totalCount += element.count;
          state.totalPrice += (element.count*element.originalPrice);
        }
      }) 
    }
  },
  actions: {
    GET_LIST_DATA(context){
      axios.get("http://api.kudesoft.cn/tdk/goods").then((res)=>{
        console.log(res)
        context.commit("GET_LIST_DATA",res.data.data.data.list)
      }).catch(()=>{

      })
    },
    ADD_ITEM_TO_CART(context,item){
      context.commit("ADD_ITEM_TO_CART",item);
    },
    CHANGE_ITEM_STATUS(context,item){
      context.commit("CHANGE_ITEM_STATUS",item)
    },
    CHANGE_ALL_SELECTED(context,boolean){
      context.commit("CHANGE_ALL_SELECTED",boolean);
    }
  },
  modules: {
  }
})
